package util;

import pojo.Employee;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class JDBCUtil {
    public static Connection connection;
    static {
        try {
            Class.forName(Config.driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        try {
            connection = DriverManager.getConnection(Config.url, Config.username, Config.password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    private static Connection con() throws SQLException {
            return connection;
    }

    private static PreparedStatement ps(String sql,Object... params) throws SQLException {
            PreparedStatement ps=con().prepareStatement(sql);
            int i=0;
            for(Object o:params){
                i++;
                ps.setObject(i,o);
            }
            return ps;
    }
    private static ResultSet rs(String sql,Object... params)throws SQLException{
          return ps(sql,params).executeQuery();
    }





    public static void  ex(String sql,Object... params){
        try {
            ps(sql,params).execute();
        }catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }
    }
    public static<T> List list(String sql,Class clazz,Object...  prams) {
       try {
           ResultSet rs=rs(sql,prams);
           List<T> list=new ArrayList<>();
           while (rs.next()){
             list.add((T)ResultSetToBean.copy(rs,clazz));
           }
           return list;
       }catch (Exception e){
           throw new RuntimeException(e.getMessage());
       }
    }

    public static<T> T one(String sql,Class clazz,Object...  prams){
        List list=list(sql,clazz,prams);
        return (T)(list.size()!=0?list.get(0):null);
    }


    public static void main(String[] args) throws Exception {
         //Integer[] arr=new Integer[3];
         Employee employee=one("select * from employee where 1=?",Employee.class,1);
         System.out.println(employee.getName());
    }



}
